<?php
    Yii::import('application.models.geo.GeoActiveRecord');
    /**
    * This is the model class for table "geo".
    *
    * The followings are the available columns in table 'geo':
    * @property string $id
    * @property string $from
    * @property string $to
    * @property string $city
    * @property string $city_id
    */

    class Geo extends GeoActiveRecord
    {
        /**
        * Returns the static model of the specified AR class.
        * @param string $className active record class name.
        * @return Geo the static model class
        */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
        * @return string the associated database table name
        */
        public function tableName()
        {
            return 'geo';
        }

        /**
        * @return array validation rules for model attributes.
        */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
                array('from, to, ip_from, ip_to', 'required'),
                array('from, to, city_id', 'length', 'max'=>10),
                array('city, latlng, region, city_google', 'length', 'max'=>255),
                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('id, from, to, city, city_id', 'safe', 'on'=>'search'),
            );
        }

        /**
        * @return array relational rules.
        */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
                'cityModel' => array(self::BELONGS_TO, 'City', 'city_id'),
            );
        }

        /**
        * @return array customized attribute labels (name=>label)
        */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'from' => 'From',
                'to' => 'To',
                'city' => 'City',
                'city_id' => 'City',
            );
        }

        /**
        * Retrieves a list of models based on the current search/filter conditions.
        * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
        */
        public function search()
        {
            // Warning: Please modify the following code to remove attributes that
            // should not be searched.

            $criteria=new CDbCriteria;

            $criteria->compare('id',$this->id,true);
            $criteria->compare('from',$this->from,true);
            $criteria->compare('to',$this->to,true);
            $criteria->compare('city',$this->city,true);
            $criteria->compare('city_id',$this->city_id,true);

            return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
            ));
        }


        public function ip2decimal($ip){
            return sprintf("%u", ip2long($ip));     
        }

        public function decimal2ip($decimal_ip){
            $b=array(0,0,0,0);
            $c = 16777216.0;
            $decimal_ip += 0.0;
            for ($i = 0; $i < 4; $i++) {
                $k = (int) ($decimal_ip / $c);
                $decimal_ip -= $c * $k;
                $b[$i]= $k;
                $c /=256.0;
            };
            $d=join('.', $b);
            return($d);        
        }

        /**
        * Lấy city name từ google
        * 
        * @param mixed $latlng
        */
        public function getCityByGoogle($latlng){

            Yii::import('ext.Curl');
            $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={$latlng}&sensor=false";
            $curl = new Curl($url);
            $data = $curl->run();
            $datas = json_decode($data, TRUE);

            $data = current($datas['results']);
            if(!$data) return NULL;

            if(isset($data['formatted_address'])){
                $addr = $data['formatted_address'];
            }else{
                $addr = $data['address_components']['formatted_address'];
            }

            $addrs = explode(',', $addr);
            $city = $addrs[count($addrs)-2];
            $city = str_replace('province', '', $city);
            return trim($city);
        }


        /**
        * Lấy city từ ip hoặc decimal ip
        * 
        * @param string $decimal_ip ip or decimal ip
        * @return City
        */
        public function getCityDataByIp($decimal_ip){
            if(preg_match('{^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$}', $decimal_ip)){
                $decimal_ip = $this->ip2decimal($decimal_ip);
            }

            if(!is_numeric($decimal_ip)) return City::model()->findByPk(1);

            $geo = Geo::model()->with('cityModel')->find("`from` <= :decimal_ip AND `to` >= :decimal_ip", array(
                ':decimal_ip' => $decimal_ip,
            ));
            return $geo ? $geo->cityModel : City::model()->findByPk(1);
        }
}